'use strict';

/**
 * 工具类
 */

var request = require('request');
var fs = require('fs');
var path = require('path');

var __utils = {};
module.exports = __utils;

/**
 * refre http://stackoverflow.com/questions/25344879/uploading-file-using-post-request-in-node-js
 *
 * 发送 multi-part, form表单
 * @url
 * @json 非文件部分
 * @fileName
 * @fileUri null 时采用默认图片文件
 * @cb {function} cb(err,res,body)
 */
__utils.post_formMultipart = function (url, json, fileName, fileUri, cb) {
  var formData = json;
  if (!fileUri) {
    fileUri = path.join(__dirname, './__mock.jpg');
  }
  formData[fileName] = fs.createReadStream(fileUri);
  request.post(url, {
    formData: formData
  }, function (err, res, body) {
    cb(err, res, body);
  });
};

__utils.post_json = function (url, json, cb) {
  var opt = {
    uri: url,
    method: 'POST',
    json: json
  };
  request(opt, function (err, res, data) {
    cb(err, res, data);
  });
};

/**
 * 读取文件到 Buffer
 * @param url
 * @returns {*}
 */
__utils.readFileAsBuffer = function (url) {
  var buf = fs.readFileSync(url);
  return buf;
};

/**
 * buf to base64 string
 * @param buf
 * @returns {string|*}
 */
__utils.bufToBase64 = function (buf) {
  return buf.toString('base64');
};